package com.niit.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC工具类
 * 
 * @author Administrator
 *
 */
public class JDBCUtil {

	/**
	 *
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			if (conn == null) {
				InputStream resource = Thread.currentThread().getContextClassLoader()
						.getResourceAsStream("/jdbc.properties");
				Properties properties = new Properties();
				properties.load(resource);
				String dirverClass = properties.getProperty("driverClass");
				String url = properties.getProperty("url");
				String username = properties.getProperty("user");
				String password = properties.getProperty("password");
				Class.forName(dirverClass);
				conn = DriverManager.getConnection(url, username, password);
				return conn;
			}
		} catch (Exception e) {
			System.out.println("数据库连接失败.......");
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 
	 * 
	 * @param conn
	 * @param st
	 */
	public static void closeDB(Connection conn, Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * 
	 * @param conn
	 * @param st
	 * @param rs
	 * @throws SQLException
	 */
	public static void closeDB(Connection conn, Statement st, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
